package com.lcb.jmm.atomic;

import com.lcb.jmm.volatiledome.UnsafeInstance;
import sun.misc.Unsafe;

/****
 * @Author:刘长柏
 * @Date: 2021-01-05 14:31
 * @Description:属性原子修改器
 *****/
public class AtomicStudentAgeUpdater {

    private String name;
    private volatile int age;

    private static final Unsafe unsafe = UnsafeInstance.reflectGetUnsafe();

    private static final long valueOffset;

    static {
        try {
            valueOffset = unsafe.objectFieldOffset(AtomicStudentAgeUpdater.class.getDeclaredField("age"));
            System.out.println("valueOffset:--->" + valueOffset);
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    public void compareAndSwapAge(int old, int target) {
        unsafe.compareAndSwapInt(this, valueOffset, old, target);
    }

    public AtomicStudentAgeUpdater(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public int getAge() {
        return this.age;
    }

    public static void main(String[] args) {
        AtomicStudentAgeUpdater atomicStudentAgeUpdater = new AtomicStudentAgeUpdater("杨哥", 18);

        atomicStudentAgeUpdater.compareAndSwapAge(18,19);

        System.out.println(atomicStudentAgeUpdater.getAge());
    }

}
